package cn.dnuifood_cjy.dnuifood_16110100529.controller;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import cn.dnuifood_cjy.dnuifood_16110100529.Adapter.CommentAdapter;
import cn.dnuifood_cjy.dnuifood_16110100529.Adapter.FoodAdapter;
import cn.dnuifood_cjy.dnuifood_16110100529.JavaBean.CommentBean;
import cn.dnuifood_cjy.dnuifood_16110100529.JavaBean.FoodBean;
import cn.dnuifood_cjy.dnuifood_16110100529.JavaBean.Success;
import cn.dnuifood_cjy.dnuifood_16110100529.R;
import cn.dnuifood_cjy.dnuifood_16110100529.listener.OnRetrofitListener;
import cn.dnuifood_cjy.dnuifood_16110100529.model.CollectModel;
import cn.dnuifood_cjy.dnuifood_16110100529.model.FoodModel;
import cn.dnuifood_cjy.dnuifood_16110100529.model.UserModel;


public class FoodActivity extends AppCompatActivity implements OnRetrofitListener<FoodBean> {
    private MenuItem item1;
    private Menu menu;
    private FoodBean foodInfo;
    private RecyclerView recyclerView;
    private FoodAdapter foodAdapter;
    private BaseActivity baseActivity;
    private SharedPreferences sharedPreferences;
    private String user_id,id,foodname,food_id,collect;
    private ImageButton collect_1;
    private TextView foodname1,intro,price;
    private ImageView pic;
    private Context mContext;
    Success success;
    CommentAdapter commentAdapter;
    EditText editText;
    Button addComment,add;
    Gson gson;
    public FoodActivity(){
        this.mContext = mContext;

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState);
        setContentView(R.layout.food_adapter);

        id = getIntent().getStringExtra("shop_id");
        foodname = getIntent().getStringExtra("foodname");
        food_id = getIntent().getStringExtra("food_id");
        Toast.makeText(FoodActivity.this,food_id,Toast.LENGTH_SHORT).show();

        initData(food_id);

    }

    void initData(String food_id){
        FoodModel foodModel = new FoodModel();
        foodModel.getFoodById(food_id,this);//访问服务器请求
    }


    //生成Menu的对象
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //创建菜单
        getMenuInflater().inflate(R.menu.food_list_collect,menu);
        this.menu=menu;
        //菜单创建完毕后向服务器发送请求，判断是否已经收藏
        menu.findItem(R.id.item_collect1).setTitle(foodname);
        isCollected(menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //实现"显示收藏还是取消收藏"
        switch (item.getItemId()){
            case R.id.item_collect:
                String title = item.getTitle().toString();
                if (title.equals("收藏"))
                {
                    //收藏
                    collectFood(menu);
                    collect_1.setImageResource(R.drawable.tab_find_collect_press);
                }
                else
                {
                    //取消收藏
                    uncollectFood(menu);
                    collect_1.setImageResource(R.drawable.tab_find_collect_normal);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    private void initData1(){
        foodname1.setText(foodInfo.getFoodname());
        price.setText(foodInfo.getPrice()+"元");
        intro.setText(foodInfo.getIntro());
        Picasso.get().load(UserModel.Constants.BASE_URL+foodInfo.getPic()).into(pic);
        collect_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (menu.findItem(R.id.item_collect).getTitle().equals("收藏"))
                {
                    //收藏
                    collectFood(menu);
                    collect_1.setImageResource(R.drawable.tab_find_collect_press);
                }
                else
                {
                    //取消收藏
                    uncollectFood(menu);
                    collect_1.setImageResource(R.drawable.tab_find_collect_normal);
                }
            }
        });

    }

    void initViews(){
        foodname1=(TextView) findViewById(R.id.collect_name);
        intro=(TextView) findViewById(R.id.food_intro1);
        pic=(ImageView)findViewById(R.id.food_pic1);
        price=(TextView) findViewById(R.id.price1);
        collect_1= findViewById(R.id.collect_button);
        addComment= findViewById(R.id.button4);
        recyclerView=findViewById(R.id.comment_list);
        recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),1));
        commentAdapter=new CommentAdapter();
        recyclerView.setAdapter(commentAdapter);
        initRecycler();
    }

    private void initRecycler() {
        new AsyncTask<String, Void, Void>() {
            List<CommentBean> commentsList;


            @Override
            protected void onPostExecute(Void aVoid) {

                super.onPostExecute(aVoid);
//                recyclerView.setAdapter(new CommentAdapter());
                System.out.println(commentsList.toString());
                commentAdapter.setList(commentsList);
                commentAdapter.notifyDataSetChanged();
                if (!commentsList.isEmpty())
                {
                    sharedPreferences=getSharedPreferences("INFOR", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor=sharedPreferences.edit();
                    editor.putString("itemid",Integer.toString(commentsList.get(0).getItem_id()));
                    editor.commit();
                }

            }

            @Override
            protected Void doInBackground(String... strings) {
                try {
                    URL url = new URL(strings[0]);
                    URLConnection connection = url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        System.out.println("评论返回信息"+line );
                        commentsList = new Gson().fromJson(line, new TypeToken<List<CommentBean>>(){}.getType());
//                        System.out.println();
//                        System.out.println(commentsList.toString());
                        bufferedReader.close();
                        inputStreamReader.close();
                        inputStream.close();
                    }

                } catch (MalformedURLException e) {

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute("http://172.24.10.175:8080/foodService/getAllCommentsByFood.do?food_id="+food_id);
    }


    private void isCollected(Menu menu){
        String food_id = getIntent().getStringExtra("food_id");
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        String user_id = sharedPreferences.getString("user_id","user_id");
        CollectModel collectModel = new CollectModel();
        collectModel.isCollect(user_id,food_id,"1",menu);
    }

    private void collectFood(Menu menu){
        String food_id = getIntent().getStringExtra("food_id");
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        String user_id = sharedPreferences.getString("user_id","user_id");
        CollectModel collectModel = new CollectModel();
        collectModel.userCollectFood(user_id,food_id,menu);

    }

    private void uncollectFood(Menu menu){
        String food_id = getIntent().getStringExtra("food_id");
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        String user_id = sharedPreferences.getString("user_id","user_id");
        CollectModel collectModel = new CollectModel();
        collectModel.unCollectFood_01(user_id,food_id,menu);
    }

    @Override
    public void onSuccess(FoodBean object, int flag) {
        this.foodInfo=object;

        initViews();
        initData1();
        initEvent();
    }

    private void initEvent() {
        addComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(FoodActivity.this);
                final AlertDialog dialog = builder.create();
                View dialogView = View.inflate(FoodActivity.this,R.layout.dialog_addcomment, null);

                //设置对话框布局
                dialog.setView(dialogView);
                editText=dialogView.findViewById(R.id.editText);
                dialog.show();
                add=dialogView.findViewById(R.id.button);
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new AsyncTask<String, Void, Void>() {
                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                if (success.getSuccess().equals("1"))
                                {
                                    Toast.makeText(FoodActivity.this, "成功", Toast.LENGTH_SHORT).show();
//                                    commentAdapter.setList();
                                    initRecycler();
                                }
                                else
                                    Toast.makeText(FoodActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                            String line = new String();
                            @Override
                            protected Void doInBackground(String... strings) {
                                try {
                                    URL url = new URL(strings[0]);
                                    URLConnection connection = url.openConnection();
                                    InputStream inputStream = connection.getInputStream();
                                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                                    while ((line = bufferedReader.readLine()) != null) {
                                        System.out.println("添加评论返回信息" + line);
                                        gson = new Gson();
                                        success = gson.fromJson(line, Success.class);
                                        bufferedReader.close();
                                        inputStreamReader.close();
                                        inputStream.close();
                                    }
                                } catch (MalformedURLException e) {

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }
                        }.execute("http://172.24.10.175:8080/foodService/insertComment.do?item_id="+sharedPreferences.getString("itemid","")+"&content="+editText.getText());
                    }
                });

            }
        });



    }

    @Override
    public void onFailure(String msg) {
        Toast.makeText(FoodActivity.this,"网络连接失败",Toast.LENGTH_SHORT).show();
    }
}
